import React from 'react';
import ReactDOM from 'react-dom';
import Dialog from '../../../../node_modules/react-bootstrap/lib/Modal';
import Button from "../../../../node_modules/react-bootstrap/lib/Button";
import Modal from "../../../../node_modules/react-bootstrap/lib/Modal";
import HttpRequest from './../HttpRequest.js';
import dialogManager from './../dialogManager.jsx';
import Input from 'react-bootstrap/lib/Input';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import validate from'../../../../common/validate.js'
import Checkbox from '../component/formElement/Checkbox.jsx';
import msgFrontAgent from  '../msgFrontAgent.js';

let NewProjectDlg = React.createClass({
    getInitialState: function () {
        return {
            open: false,
            allProjects:[],
            submit_btn:true
        }
    },
    componentWillMount:function(){
        HttpRequest.getCurrentUser().success(function (res) {
            if (res.code == 0) {
                this.setState({
                    current_user: res.data
                });
            }
        }.bind(this))
    },
    componentDidMount:function() {
        HttpRequest.getAllProjects().success(function(data){
            if(data.code != 500){
                this.setState({
                    allProjects:data.data
                });
            }
        }.bind(this)).error(function(error){
            toastr.error(null, "发生错误："+ JSON.stringify(error));
        });
    },
    auto_focus: function(){
        let inputDom;
        let nameInputRef = this.refs["pjtName"];
        if(nameInputRef){
            inputDom = ReactDOM.findDOMNode(nameInputRef);
        }
        if(inputDom){
            inputDom.childNodes[1].focus();
        }
    },
    handleCompleted: function () {
        if(this.validate()){
            var projectInfo = {
                'namespace':this.refs['project_namespace'].getValue(),
                'name': this.refs['pjtName'].getValue(),
                'title': this.refs['pjtTitle'].getValue(),
                'description': this.refs['pjtDescription'].getValue()
            };
            window.loading();
            HttpRequest.createProject(projectInfo).success(function (msg) {
                if(msg.code != 500){
                    toastr.success(null, "新建项目完成");
                    window.removeLoading();
                    this.handleClose();
                    this.props.newProjectComplete(msg.data);
                    if(this.refs['create_workspace'].isChecked()){
                        toastr.success(null, "开始创建工作空间");
                        var options = {
                            work_name: msg.data.project.name,
                            project_id: msg.data.project._id,
                            //git_source: 0,
                            //git_url: "",
                            userId: this.state.current_user.shortid,
                            userName: this.state.current_user.loginname
                        };
                        HttpRequest.addWorkspace(options).success(function (res) {
                            if (res.code == 200) {
                                toastr.success(null, "工作空间创建完成");
                                //msgFrontAgent.order(res.data.task_id, function (data) {
                                //    if (data.err) {
                                //        toastr.error(null, data.err, {timeOut: 0});
                                //    } else {
                                //        toastr.success(null, data.body.msg);
                                //    }
                                //});
                            } else {
                                toastr.error(null, "工作空间创建错误");
                            }

                        }).error(function (error) {
                            toastr.error(null, "工作空间创建错误");
                        });
                    }
                }else{
                    window.removeLoading();
                    toastr.error(null, "新建项目失败");
                }

            }.bind(this)).error(function (msg) {
                toastr.error(null, "新建项目失败");
            });
        }
    },
    handleOpen: function () {

        this.setState({open: true}, this.auto_focus);
    },

    handleClose: function () {
        this.setState({
            open: false,
            submit_btn:true
        });
    },
    opeUncancelled:function(){
        this.setState({
            open: true,
            disabled: "disabled"
        });
    },

    validate:function() {
        var thisOb = this;
        thisOb.refs['warning'].innerHTML = ("");
        var project_name = thisOb.refs['pjtName'].getValue();
        var project_title = thisOb.refs['pjtTitle'].getValue();
        var namespace = this.refs['project_namespace'].getValue();
        if(!validate.notEmpty(project_name)){
            thisOb.refs['warning'].innerHTML = ("项目名称不能为空！");
            return false;
        }else if(!validate.noSpacing(project_name)){
            thisOb.refs['warning'].innerHTML = ("项目名称不能包含空格！");
            return false;
        }else if(!validate.variableNameFormat(project_name)){
            thisOb.refs['warning'].innerHTML = ("项目名称3~30位，只允许包含数字、字母、'.'和'_',且不能以数字或'.'开头！");
            return false;
        }
        for(var index in  this.state.allProjects)
        {
            if(this.state.allProjects[index].name == project_name && this.state.allProjects[index].namespace == namespace){
                thisOb.refs['warning'].innerHTML = ("项目名称"+project_name+"已经存在，请重新命名！");
                return false;
            }
        }

        if(!validate.notEmpty(project_title)){
            thisOb.refs['warning'].innerHTML = ("项目标题不能为空！");
            return false;
        }else if(project_title.length > 25){
            thisOb.refs['warning'].innerHTML = ("项目标题长度不能大于30！");
            return false;
        }

        thisOb.setState({
            submit_btn: false
        });
        return true;
    },
    render() {
        var namespace_options = [];
        if(this.state.current_user){
            var user = this.state.current_user;
            namespace_options.push(<option key = {"namespace_personal_"+user.loginname}  value={user.loginname}>{user.loginname}</option>)
        }

        return (
            <Modal
                show={this.state.open}
            >
                <Modal.Header>
                    <Modal.Title >新建项目</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Input ref="project_namespace" bsSize="small" type="select" label="命名空间" >
                        {namespace_options}
                    </Input>
                    <Input ref="pjtName" bsSize="small" type="text" label="项目名称" onChange={this.validate}/>
                    <Input ref="pjtTitle" bsSize="small" type="text" label="项目标题" onChange={this.validate}/>
                    <Input ref="pjtDescription" bsSize="small" type="textarea" label="项目简介" style={{height:"70px"}}/>
                    <Checkbox label="是否创建工作空间" ref="create_workspace" isChecked = 'true'/>
                    <span ref="warning" style={{fontSize:'5px',color:'red'}}/>
                </Modal.Body>
                <Modal.Footer>
                    <Button onClick={this.handleClose}
                            ref = 'cancel_btn'
                            style={{backgroundColor: "#555", borderColor: "#555",width:"70px",margin:'12'}}
                            bsStyle="primary">取消</Button>
                    <Button onClick={this.handleCompleted}
                            disabled = {this.state.submit_btn}
                            style={{backgroundColor: "#555", borderColor: "#555",width:"70px",margin:'12'}}
                            bsStyle="primary">确定</Button>
                </Modal.Footer>
            </Modal>

        );
    }
});
dialogManager.addDialog("new_project_dlg", NewProjectDlg);
module.exports = NewProjectDlg;